package shopBean.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FtpFile  {
	// ftp服务器地址
	private String hostname = "";
	// ftp服务器端口号默认为21
	private String port ;
	// ftp登录账号
	private String username = "";
	// ftp登录密码
	private String password = "";
	private FTPClient ftpClient = null;
	private String basePath;
	
	public String getHostname() {
		return hostname;
	}

	public void setHostname(String hostname) {
		this.hostname = hostname;
	}

	

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public FTPClient getFtpClient() {
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}
	private static Logger logger = LoggerFactory.getLogger(FtpFile.class);

	

	/**
	 * Description: 向FTP服务器上传文件 @Version1.0 Jul 27, 2008 4:31:09 PM by
	 * 崔红保（cuihongbao@d-heaven.com）创建
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param path
	 *            FTP服务器保存目录
	 * @param filename
	 *            上传到FTP服务器上的文件名
	 * @param input
	 *            输入流
	 * @return 成功返回true，否则返回false
	 */
	public boolean uploadFile(InputStream inputStream, String fileName, String pathname) {
		try {
			init();
			logger.debug("开始上传文件");
			
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			ftpClient.changeWorkingDirectory("/");
			String[] pah = (basePath+pathname).split("/");         
            // 分层创建目录
            for (String pa : pah) {
                System.out.println(pa);
                logger.debug(ftpClient.makeDirectory(pa)+"");
                // 切到到对应目录
                ftpClient.changeWorkingDirectory(pa);
            }        
			ftpClient.changeWorkingDirectory(basePath+pathname);
			ftpClient.storeFile(fileName, inputStream);
			inputStream.close();
			ftpClient.logout();
			logger.debug("上传文件成功");
		} catch (Exception e) {
			logger.error("上传文件失败",e);
			e.printStackTrace();
			return false;
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != inputStream) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}

	public boolean existFile(String path) throws IOException {
		boolean flag = false;
		FTPFile[] ftpFileArr = ftpClient.listFiles(path);
		if (ftpFileArr.length > 0) {
			flag = true;
		}
		return flag;
	}

	public boolean CreateDirecroty(String remote) throws IOException {
		boolean success = true;
		String directory = remote + "/";
		// 如果远程目录不存在，则递归创建远程服务器目录
		if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
			int start = 0;
			int end = 0;
			if (directory.startsWith("/")) {
				start = 1;
			} else {
				start = 0;
			}
			end = directory.indexOf("/", start);
			String path = "";
			String paths = "";
			while (true) {
				String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
				path = path + "/" + subDirectory;
				if (makeDirectory(subDirectory)) {
					changeWorkingDirectory(subDirectory);
				} else {
					logger.debug("创建目录[" + subDirectory + "]失败");
					changeWorkingDirectory(subDirectory);
				}
				

				paths = paths + "/" + subDirectory;
				start = end + 1;
				end = directory.indexOf("/", start);
				// 检查所有目录是否创建完毕
				if (end <= start) {
					break;
				}
			}
		}
		return success;
	}

	public boolean changeWorkingDirectory(String directory) {
		boolean flag = true;
		try {
			flag = ftpClient.changeWorkingDirectory(directory);
			if (flag) {
				logger.debug("进入文件夹" + directory + " 成功！");

			} else {
				logger.debug("进入文件夹" + directory + " 失败！开始创建文件夹");
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return flag;
	}
	 public boolean makeDirectory(String dir) {
         boolean flag = true;
         try {
             flag = ftpClient.makeDirectory(dir);
             if (flag) {
                 logger.debug("创建文件夹" + dir + " 成功！");

             } else {
                 logger.debug("创建文件夹" + dir + " 失败！");
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return flag;
     }

	public void init() throws Exception {
		ftpClient = new FTPClient();
		ftpClient.setControlEncoding("utf-8");
		try {
			logger.debug("connecting...ftp服务器:" + hostname + ":" + this.port);
			ftpClient.connect(hostname, Integer.valueOf(port.trim())); // 连接ftp服务器
			ftpClient.login(username, password); // 登录ftp服务器
			int replyCode = ftpClient.getReplyCode(); // 是否成功登录服务器
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				logger.debug("connect failed...ftp服务器:" + hostname + ":" + port);
			}
			logger.debug("connect successfu...ftp服务器:" + hostname + ":" + port);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			logger.error("连接服务器异常",e);;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("连接服务器异常",e);;
		}
	}
}
